<script setup lang="ts">
import router from "@/apps/client/router.js";
import { computed, ref, watch } from "vue";

import CubicleReservationRecord from "@/apps/client/components/CubicleReservationRecord.vue";
import InstrumentReservationRecord from "@/apps/client/components/InstrumentReservationRecord.vue";
import {clockInByReservationId, clockOutByReservationId, getReservations} from "@/apps/client/utils/roomApi";
import QRCodeScanner from "@/apps/client/views/QRCodeScanner.vue";
import { showNotify } from "vant";
import AutoReservationRecordCard from "@/apps/client/components/AutoReservationRecordCard.vue";

// 页面控制变量
const active = ref(0); // 0:全部 1:实验室 2:会议室 3:仪器
const showQRCode = ref(false);
const scanResult = ref(null);

// 维护每个分类的数据
const pageMap = ref({ ALL: 1, CUBICLE_LAB: 1, CUBICLE_MEETING: 1, INSTRUMENT: 1 });
const dataMap = ref({ ALL: [], CUBICLE_LAB: [], CUBICLE_MEETING: [], INSTRUMENT: [] });
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

const typeMap = ["ALL", "CUBICLE_LAB", "CUBICLE_MEETING", "INSTRUMENT"];
const currentType = computed(() => typeMap[active.value]);

const onClickLeft = () => router.back();

// 扫码处理
// const qrString = sessionStorage.getItem("qr-data");
//
// if (qrString) {
//   qr(qrString);
//   sessionStorage.setItem("qr-data", "");
// } else {
//   updateReservation(true);
// }

qr()

async function qr() {
  const qrStr = sessionStorage.getItem("qr-data");
  const reservationStr = sessionStorage.getItem("reservation");
  const op = sessionStorage.getItem("op");

  if (!qrStr || !reservationStr || !op) {
    return ;
  }

  // 清理 sessionStorage 中的临时数据
  sessionStorage.removeItem("qr-data");
  sessionStorage.removeItem("reservation");
  sessionStorage.removeItem("op");

  let qrJson, reservationJson;
  try {
    qrJson = JSON.parse(qrStr);
    reservationJson = JSON.parse(reservationStr);
  } catch (e) {
    console.log(e)
    showNotify({ type: "danger", message: "二维码或预约信息格式错误" });
    return;
  }

  let match: boolean;
  if (reservationJson.type === "INSTRUMENT") {
    console.log(reservationJson)
    console.log(qrJson)
    // alert("INSTRUMENT   " + JSON.stringify(reservationJson) + "  " + JSON.stringify(qrJson))
    if (qrJson.instrumentId == null || reservationJson.instrumentId == null){
      showNotify({ type: "danger", message: "二维码或预约信息格式错误" });
      return;
    }
    match = (
        qrJson.instrumentId === reservationJson.instrumentId
    )
  } else {
    match = (
        qrJson.roomId === reservationJson.roomId &&
        qrJson.cubicleNumber === reservationJson.cubicleNumber
    );
  }

  if (!match) {
    showNotify({ type: "danger", message: "二维码与预约信息不匹配" });
    return;
  }

  const apiFunc = op === "in" ? clockInByReservationId : clockOutByReservationId;
  const successMsg = op === "in" ? "签到成功" : "签退成功";

  const res = await apiFunc({ reservationId: reservationJson.id });
  if (res.code === 200) {
    setTimeout(() => {
      updateReservation(true);
    }, 1000);
    showNotify({ type: "success", message: successMsg });

  } else {
    showNotify({ type: "danger", message: res.msg });
  }


}

// function qr() {
//   let qrJson;
//   try {
//     qrJson = JSON.parse(qrString);
//     if (!(qrJson.floorId && qrJson.roomNumber && qrJson.cubicleNumber)) {
//       updateReservation(true);
//       return showNotify({ type: "danger", message: "二维码解析失败" });
//     }
//   } catch (e) {
//     updateReservation(true);
//     return showNotify({ type: "danger", message: "二维码解析失败" });
//   }
//
//   alert("扫码结果: 签到 " + qrString);
//   handleReservations(qrJson);
// }

// async function handleReservations(qrJson) {
//   try {
//     const body = await cubicleSigned({
//       floorId: qrJson.floorId,
//       roomNumber: qrJson.roomNumber,
//       cubicleNumber: qrJson.cubicleNumber,
//     });
//
//     if (body.code === 200) {
//       showNotify({ type: "success", message: "成功" });
//     } else {
//       showNotify({ type: "danger", message: body.msg });
//     }
//
//     await updateReservation(true);
//   } catch (error) {
//     showNotify({ type: "danger", message: "操作失败，请重试" });
//   }
// }

// 拉取数据
async function updateReservation(reset = false) {
  const type = currentType.value;

  if (reset) {
    pageMap.value[type] = 1;
    dataMap.value[type] = [];
    finished.value = false;
  }

  loading.value = true;

  try {
    const page = pageMap.value[type];
    const res = await getReservations(type, 10, page);
    const newRecords = res.data.records;

    dataMap.value[type] = reset
        ? newRecords
        : [...dataMap.value[type], ...newRecords];

    if (newRecords.length < 10) {
      finished.value = true;
    } else {
      pageMap.value[type]++;
    }
  } catch (e) {
    showNotify({ type: "danger", message: "加载失败" });
    finished.value = true;
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
}

// 上拉加载
function onLoad() {
  updateReservation(false);
}

// 下拉刷新
function onRefresh() {
  refreshing.value = true;
  updateReservation(true);
}

// tab 切换监听
watch(active, () => {
  const type = currentType.value;
  if (dataMap.value[type].length === 0) {
    updateReservation(true);
  }
});

// 取消预约刷新
function handleCancelReservation() {
  updateReservation(true);
}

// 扫码成功
function handleScanSuccess(text: string) {
  alert(`扫码结果：${text}`);
  scanResult.value = text;
  showQRCode.value = false;
}
</script>


<template>
  <div style="background: #EEEEEE7F; min-height: 100vh;">
    <QRCodeScanner v-if="showQRCode" @on-success="handleScanSuccess" />

    <van-nav-bar
        title="我的预约"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />

    <van-tabs v-model:active="active">
      <van-tab title="全部">
        <van-pull-refresh :model-value="refreshing" @refresh="onRefresh">
          <van-list
              :loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
          >
            <AutoReservationRecordCard
                v-for="item in dataMap.ALL"
                :key="item.id"
                :data="item"
                @cancel="handleCancelReservation"
                style="margin-top: 8px"
            />
          </van-list>
        </van-pull-refresh>
      </van-tab>

      <van-tab title="实验室预约">
        <van-pull-refresh :model-value="refreshing" @refresh="onRefresh">
          <van-list
              :loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
          >
            <CubicleReservationRecord
                v-for="item in dataMap.CUBICLE_LAB"
                :key="item.id"
                :data="item"
                @cancel="handleCancelReservation"
                style="margin-top: 8px"
            />
          </van-list>
        </van-pull-refresh>
      </van-tab>

      <van-tab title="会议室预约">
        <van-pull-refresh :model-value="refreshing" @refresh="onRefresh">
          <van-list
              :loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
          >
            <CubicleReservationRecord
                v-for="item in dataMap.CUBICLE_MEETING"
                :key="item.id"
                :data="item"
                @cancel="handleCancelReservation"
                style="margin-top: 8px"
            />
          </van-list>
        </van-pull-refresh>
      </van-tab>

      <van-tab title="仪器预约">
        <van-pull-refresh :model-value="refreshing" @refresh="onRefresh">
          <van-list
              :loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
          >
            <InstrumentReservationRecord
                v-for="item in dataMap.INSTRUMENT"
                :key="item.id"
                :data="item"
                style="margin-top: 8px"
            />
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
  </div>
</template>



<style scoped>

</style>